#coding=utf-8
from __future__ import unicode_literals
import requests
from bs4 import BeautifulSoup
from wxpy import *
import pymysql
import sys,io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header

#二维码登陆
#bot = Bot(cache_path=True)
#bot = Bot(console_qr=1,cache_path=True)

def get_html(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
    }
    response = requests.get(url, headers = headers)
    if response.status_code == 200:
        return response.text
    else:
        print('无数据！')
    return None


# 解析网页内容
def parse_html(html):
    soup = BeautifulSoup(html, 'lxml')
    i = 0
    for item in soup.select('tr')[2:3]:
        yield{
            'time':item.select('td')[i].text,
            'issue':item.select('td')[i+1].text,
            'red_1':item.select('td em')[0].text,
            'red_2':item.select('td em')[1].text,
            'red_3':item.select('td em')[2].text,
            'red_4': item.select('td em')[3].text,
            'red_5': item.select('td em')[4].text,
            'red_6': item.select('td em')[5].text,
            'blue': item.select('td em')[6].text,
            'First_prize_num': item.select('td')[i+4].text,
            'Sec_prize_num': item.select('td')[i+5].text,
        }

# 将数据写入excel表
def get_info():

    url = 'http://kaijiang.zhcw.com/zhcw/html/ssq/list.html'
    html = get_html(url)
    
    list_info = []

    for item in parse_html(html):
        red_ball = [int(item['red_1']), int(item['red_2']), int(item['red_3']), int(item['red_4']), int(item['red_5']), int(item['red_6'])]
        list_info.extend(['开奖日期: '+item['time'],'期号: '+item['issue'],'红球: '+str(red_ball),'蓝球: '+item['blue'],'一等奖: '+item['First_prize_num'][0],'二等奖: '+item['Sec_prize_num']])

    #print(list_info)
    return list_info

def compare_data():

    issue = get_info()[1].split(':')[1]
    #print(issue)
   
    #connect to database 
    database = pymysql.connect(host='localhost', user='root', passwd='', db='lottery', charset='utf8')
    cursor = database.cursor()

    #check red ball
    cursor.execute('select red from ssq_my where issue='+str(issue))
    red_db = cursor.fetchone()
    if red_db:
        red_my = list(red_db)[0]
        print('我所选的红球： '+red_my)
    else:
        print('本期没有购买，错失几千万 ！！！')

    cursor.execute('select blue from ssq_my where issue='+str(issue))
    blue_db = cursor.fetchone()
    if blue_db:
        blue_my = list(blue_db)[0]
        print('我所选的蓝球： '+blue_my)

    cursor.close()
    database.commit()
    database.close()
    
    #if red_my:
    if red_db:
        print("开奖结果："+str(get_info()))
   
        list_red_my = eval((red_my))
        list_red_official = eval(get_info()[2].split(':')[1].strip())
        int_blue_my = eval((blue_my))[0]
        int_blue_official = int((get_info()[3].split(':')[1].strip()))

        red_common_num = set(list_red_my).intersection(set(list_red_official))

        if len(red_common_num) == 6 and int_blue_my == int_blue_official:
            print("中奖情况：6 红，1 蓝")
            print("我靠，清醒清醒！！！ 一等奖！！！！！！")
            messages_return = '我靠，清醒清醒！！！ 一等奖！！！！！！'

        elif len(red_common_num) == 6 and int_blue_my != int_blue_official:
            print("中奖情况：6 红，0 蓝")
            print("二等奖！！！仔细查看！！！！！！")
            messages_return = '二等奖！！！仔细查看！！！！！！'

        elif len(red_common_num) == 5 and int_blue_my == int_blue_official:
            print("中奖情况：5 红，1 蓝")
            print("三等奖呦～～～单注3000元！！！")
            messages_return = '三等奖呦～～～单注3000元！！！5 红，1 蓝'

        elif len(red_common_num) == 5 and int_blue_my != int_blue_official:
            print("中奖情况：5 红，0 蓝")
            print("四等奖呦～～～单注200元！！！")
            messages_return = '等奖呦～～～单注200元！！！5 红，0 蓝'

        elif len(red_common_num) == 4 and int_blue_my == int_blue_official:
            print("中奖情况：4 红，1 蓝")
            print("四等奖呦～～～单注200元！！！")
            messages_return = '四等奖呦～单注200元！！！4 红，1 蓝'

        elif len(red_common_num) == 4 and int_blue_my != int_blue_official:
            print("中奖情况：4 红，0 蓝")
            print("五等奖呦～～～单注10元，再接再厉！")
            messages_return = '五等奖呦～单注10元，再接再厉！4 红，0 蓝'

        elif len(red_common_num) == 3 and int_blue_my == int_blue_official:
            print("中奖情况：3 红，1 蓝")
            print("五等奖呦～～～单注10元，再接再厉！")
            messages_return = '五等奖呦～单注10元，再接再厉！3 红，1 蓝'

        elif len(red_common_num) == 2 and int_blue_my == int_blue_official:
            print("中奖情况：2 红，1 蓝")
            print("六等奖呦～～～单注5元，别拿芝麻不当干粮！")
            messages_return ='六等奖呦～单注5元，别拿芝麻不当干粮！2 红，1 蓝'
 
        elif len(red_common_num) == 1 and int_blue_my == int_blue_official:
            print("中奖情况：1 红，1 蓝")
            print("六等奖呦～～～单注5元，别拿芝麻不当干粮！")
            messages_return ='六等奖呦～单注5元，别拿芝麻不当干粮！1 红，1 蓝'

        elif len(red_common_num) == 0 and int_blue_my == int_blue_official:
            print("中奖情况：0 红，1 蓝")
            print("六等奖呦～～～单注5元，别拿芝麻不当干粮！")
            messages_return ='六等奖呦～单注5元，别拿芝麻不当干粮！0 红，1 蓝'

        else:
            print("中奖情况："+ str(len(red_common_num)) +" 红，0 蓝")
            print("胜败乃兵家常事，大侠请重新再来！")
            messages_return = '胜败乃兵家常事，大侠请重新再来！'+ str(len(red_common_num)) +" 红，0 蓝"

        return messages_return
    else:
        print("本期没有购买，错失几千万 ！！！")
        messages_return ='本期没有购买，错失几千万 ！！！'
        return messages_return

def SendEmail():
    #compare_data()
    print ('Send Email to me ~~~')

    mail_host='smtp.163.com'
    mail_user='baiyflf1987'
    mail_pass='KZXVIDUHEBQLSISE'
    #mail_pass='Embe1mpls'

    sender = 'baiyflf1987@163.com' 
    receivers = ['421581400@qq.com']

    message = MIMEText(str(get_info()), 'plain', 'utf-8')
    message['From'] = "baiyflf1987<baiyflf1987@163.com>"
    message['To'] =  "421581400<421581400@qq.com>"
 
    subject = compare_data()
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host,25)
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(sender, receivers,message.as_string())
        print ('Email send successfully ~')

    except smtplib.SMTPException as e:
        print(e)
        print ('ERROR: Email send failed !!! Please double check !!!')

    
def wechat():
    try:
        my_friend = bot.friends().search(u'CL')[0]
        my_friend.send(get_info())

    except:
        my_friend = bot.friends().search(u'CL')[0]
        my_friend.send(u"今天信息发送失败了")


def main():
#    wechat()
    #get_info()
    #compare_data()
    SendEmail()
if __name__ == '__main__':
    main()

